package com.ctrip.cap.client.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.glassfish.jersey.client.ClientProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctrip.cap.client.RunAtServiceClient;
import com.ctrip.cap.client.impl.base.BaseClientImpl;
import com.ctrip.cap.client.property.CapClientProperties;
import com.ctrip.cap.common.exception.CapException;
import com.ctrip.cap.domain.DeviceDetect;
import com.ctrip.cap.domain.DeviceInfo;
import com.ctrip.cap.domain.JobDeviceInfo;
import com.ctrip.cap.domain.LogCase;
import com.ctrip.cap.domain.LogJob;
import com.ctrip.cap.domain.LogRunDetail;
import com.ctrip.cap.domain.LogSnapShot;
import com.ctrip.cap.domain.PreprocessDomain;
import com.ctrip.cap.exception.CapDataException;

public class CapRunAtDataServiceClientImp extends BaseClientImpl implements RunAtServiceClient {

	private static final Logger logger = LoggerFactory
			.getLogger(CapRunAtDataServiceClientImp.class);

	public CapRunAtDataServiceClientImp() {
		super();
	}

	@Override
	public Integer addCILogRunDetail(LogRunDetail logRunDetail) {

		return this.baseCall("runat/service/run/detail", logRunDetail, HttpMethodType.POST, Integer.class);

	}

	@Override
	public void updateDeviceStatus(DeviceInfo deviceInfo) {
		
		this.baseCall("runat/service/device/detail", deviceInfo, HttpMethodType.PUT);
	
	}

	@Override
	public void addWiFiIssue(DeviceDetect deviceDetect) {
		
		this.baseCall("runat/service/device/detect", deviceDetect, HttpMethodType.POST);

	}

	@Override
	public List<PreprocessDomain> getPreprocStrategy(
			PreprocessDomain preprocessDomain) {
		
		return this.baseCall("runat/service/preprocess", preprocessDomain, HttpMethodType.GET, ArrayList.class, "preprocessDomain");
		
	}

	@Override
	public void addDevicesToSql(List<JobDeviceInfo> jobDeviceInfoList) {
		
		this.baseCall("runat/service/job/device", jobDeviceInfoList, HttpMethodType.POST);
		
	}

	@Override
	public Integer createJobID(LogJob logJob) {
		
		return this.baseCall("runat/service/job", logJob, HttpMethodType.POST, Integer.class);

	}

	@Override
	public String addRunCase(LogCase logCase) {
		
		return this.baseCall("runat/service/run/case", logCase, HttpMethodType.GET, String.class);

	}

	@Override
	public void addCiLogJob(LogJob logJob) {
		
		this.baseCall("runat/service/job", logJob, HttpMethodType.PUT);
		
	}
	
	public String uploadImgFileToServer(String imagePath, String suffix) throws IOException {
		
		if(suffix!=null&&!suffix.equalsIgnoreCase(".txt")&&!suffix.equalsIgnoreCase(".png")){
			throw new CapException("not supported suffx!");
		}
		
		byte[] imageBytes = IOUtils.toByteArray(Files.newInputStream(Paths
				.get(imagePath)));

		String guid = UUID.randomUUID().toString();
		String basicUrl = CapClientProperties.CAP_DATA_FILE_UPLOAD;
		String base64 = new String(Base64.encodeBase64(imageBytes),
				CapClientProperties.DEFAULT_ENCODING);
		Client client = ClientBuilder.newClient();

		String requestString = CapClientProperties.FILE_SEVICE_REQUEST_BODY;

		WebTarget webTarget = client.target(basicUrl);

		Response response = webTarget
				.request()
				.header("SOAPAction", "UploadFile")
				.property(ClientProperties.CONNECT_TIMEOUT,
						CapClientProperties.TIMEOUT_MS)
				// .header("Content-Type", "text/xml; charset=utf-8")
				.post(Entity.entity(
						String.format(requestString, guid, suffix, "1", guid, base64),
						MediaType.TEXT_XML_TYPE));

		if (response.getStatus() != 200 && response.getStatus() != 202) {
			throw new CapDataException(response.readEntity(String.class));

		}
		logger.debug("" + response.getStatus());
		return guid;
	}

	public String uploadImgFileToServer(String imagePath) throws IOException {
		return uploadImgFileToServer(imagePath, CapClientProperties.PNG_SUFFIX);
	}

	public void uploadImgFileToDB(LogSnapShot logSnapShot) {
		
		this.baseCall("runat/service/img", logSnapShot, HttpMethodType.POST);

	}

	public static void main(String[] args) {
		try {

			CapRunAtDataServiceClientImp client = new CapRunAtDataServiceClientImp();
			// client.getPreprocStrategy(new PreprocessDomain("HTC M8St",
			// "runat"));

			String guid = client.uploadImgFileToServer("D:\\traversal\\tree\\traversal_tree.json",".txt");
			System.out.println(guid);
//			client.uploadImgFileToDB(new LogSnapShot(
//					CapClientProperties.CAP_DATA_FILE_DOWNLOAD + "/" + guid
//							+ ".png", new Date(), guid));

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

}
